package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.JOptionPane;

import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import models.SupplierModel;
import system.View;

public class SupplierController extends AbstractMenuItemController {
	private SupplierModel supplier = new SupplierModel();

	public SupplierController(View v) {
		super(v);
		abstractModel = supplier;
		supplier.addExceptionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();

		if (actionCommand.equals("Delete Supplier"))
			showDialogWindow(new DeleteTupleDialog(view, actionCommand, "Key",
					new String[] { "Supplier Name: " }, this));
		else if (actionCommand.equals("Insert Supplier"))
			showDialogWindow(new InsertTupleDialog(view, actionCommand,
					"Supplier", new String[] { "Supplier Name: ", "Address: ",
							"City: ", "Status: " }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		if (s.size() != 4)
			return VALIDATIONERROR;

		try {
			String supName;
			String address;
			String city;
			String status;
			if (s.get(0).trim().length() != 0)
				supName = s.get(0).trim();
			else return VALIDATIONERROR;
			if (s.get(1).length() != 0)
				address = s.get(1).trim();
			else return VALIDATIONERROR;
			if (s.get(2).length() != 0)
				city = s.get(2).trim();
			else return VALIDATIONERROR;
			if (s.get(3).length() != 0)
				status = s.get(3).trim();
			else return VALIDATIONERROR;

			view.updateStatusBar("Inserting Supplier...");

			if (supplier.insert(supName, address, city, status))
				return operationSuccess();
			else {
				JOptionPane.showMessageDialog(view, "Supplier name may already exists, or status is not 'active' or 'inactive' ", "Error", JOptionPane.ERROR_MESSAGE);
				return operationFailure();
			}
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}

	@Override
	public int validateDelete(Vector<String> s) {
		if (s.size() != 1)
			return VALIDATIONERROR;
		try {
			String supName;
			if (s.get(0).trim().length() != 0)
				supName = s.get(0).trim();
			else return VALIDATIONERROR;
			view.updateStatusBar("Deleting Supplier...");
			if (supplier.delete(supName)) return operationSuccess();
			else {
				JOptionPane.showMessageDialog(view, "Supplier doesn't exist", "Error", JOptionPane.ERROR_MESSAGE);
				return operationFailure();
			}
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}

}
